package cn.itcast.usermanage.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.itcast.usermanage.pojo.User;
import cn.itcast.usermanage.result.DataGridResult;
import cn.itcast.usermanage.result.PageResult;
import cn.itcast.usermanage.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	/**
	 * 页面跳转成功，进入用户列表界面
	 * @return
	 */
	@RequestMapping("/users")
	public String toUserList(){
		return "users";
	}
	
	/**
	 * 页面跳转成功，进入用户添加页面
	 * @return
	 */
	@RequestMapping("/user-add")
	public String toUserAdd(){
		return "user-add";
	}
	
	@RequestMapping("/list")
	@ResponseBody
	public DataGridResult<User> queryUserListByPage(
			@RequestParam(value="page",defaultValue="1")Integer page,
			@RequestParam(value="rows",defaultValue="5")Integer rows){
		//查询用户信息
		return userService.queryUserListByPage(page,rows);
	}
	
	@RequestMapping("/save")
	@ResponseBody
	public PageResult saveUser(User user){
		try{
			this.userService.saveUser(user);
			return PageResult.ok();
		}catch(Exception e){
			e.printStackTrace();
			return PageResult.error();
		}
	}
	
	@RequestMapping(value="delete",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Integer> deleteUser(@RequestParam("ids")Long[] ids){
		Map<String, Integer> result = new HashMap<>();
		try {
			//调用service的删除功能
			this.userService.deleteUserByIds(ids);
			result.put("status", 200);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("status", 500);
		}
		return result;
	}
	
	@RequestMapping(value="/export/excel",method=RequestMethod.POST)
	public ModelAndView exportExcel(
			@RequestParam(value="page",defaultValue="1")Integer page,
			@RequestParam(value="rows",defaultValue="5")Integer rows){
		//创建视图和模型对象
		ModelAndView mv = new ModelAndView("excelView");
		//查询分页数据
		DataGridResult<User> result = this.userService.queryUserListByPage(page, rows);
		//添加数据到模型
		mv.addObject("users", result.getRows());
		return mv;
	}
}
